package org.kl.bpm.service.conf;

import java.util.List;
import java.util.Map;

import org.kl.bf.utils.CRUDUtils;
import org.kl.bf.utils.KLDynamicSpecifications;
import org.kl.bpm.entity.conf.BpmProcess;
import org.kl.bpm.repository.conf.BpmProcessDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;

/**
 * 
 * @Author hqm
 * @CreateTime 2014年5月25日 下午8:40:29
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional
public class BpmProcessService {

	private BpmProcessDao bpmProcessDao;

	public BpmProcess getBpmProcess(String id) {
		return bpmProcessDao.findOne(id);
	}

	public void saveBpmProcess(BpmProcess entity) {
		bpmProcessDao.save(entity);
	}

	public void deleteBpmProcess(String id) {
		bpmProcessDao.delete(id);
	}

	public BpmProcess findByBpmConfBaseProcessDefinitionKey(String processDefinitionKey) {
		return bpmProcessDao.findByBpmConfBaseProcessDefinitionKey(processDefinitionKey);
	}

	public BpmProcess findByBpmConfBaseProcessDefinitionId(String processDefinitionId) {
		return bpmProcessDao.findByBpmConfBaseProcessDefinitionId(processDefinitionId);
	}

	public List<BpmProcess> getAllBpmProcess() {
		return bpmProcessDao.findAll();
	}

	public List<BpmProcess> findByBpmCategoryId(String bpmCategoryId) {
		return bpmProcessDao.findByBpmCategoryId(bpmCategoryId);
	}

	public Page<BpmProcess> getUserBpmProcess(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType,
			String orderType) {
		PageRequest pageRequest = CRUDUtils.buildPageRequest(pageNumber, pageSize, sortType, orderType);
		Specification<BpmProcess> spec = buildSpecification(searchParams);

		return bpmProcessDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<BpmProcess> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		Specification<BpmProcess> spec = DynamicSpecifications.bySearchFilter(filters.values(), BpmProcess.class);
		return spec;
	}

	@Autowired
	public void setBpmProcessDao(BpmProcessDao bpmProcessDao) {
		this.bpmProcessDao = bpmProcessDao;
	}

	public List<BpmProcess> getAllUserBpmProcess(Map<String, Object> searchParams, String sortType, String orderType) {
		Specification<BpmProcess> spec = KLDynamicSpecifications.buildSpecification(searchParams, BpmProcess.class);
		return bpmProcessDao.findAll(spec, CRUDUtils.buildSort(sortType, orderType));
	}

}
